import React, {Component} from 'react';
import {ajax, promptBox, toast, cacheTools} from 'nc-lightapp-front';
import './index.less'
import {chectFormAction, setFormAttrAndValue} from '../../../../../public/functions/checkFormAction'
let pk_psnjobs = []
import {saveValidate } from 'src/hrpub/common/utils/utils';
class AddForm extends Component{
    constructor(props) {
        super(props);
        this.state = {
            formVisible: false,
            step: '0',
            pk_psnjobs: [],
            editColumn: [], // 可编辑的键
            contractnum: '', // 变更前合同编号
            addSaveUrl: 'MakeAddSaveAction',
            savedData: null,
            rollBackFlag: null,
            extendParam: null,
            config: props.config
        }
    }
    // 将表单模板key值改变
    setDataBeforeFormKey (props) {
        let state = this.state
        // 改dataAfter的键名
        let meta = props.meta.getMeta()['dataBefore_add']
        let meta2 = props.meta.getMeta()['dataAfter_add']
        meta.items.map(obj => {
            obj.attrcode = obj.attrcode + '_old'
            switch (obj.attrcode) {
                case 'creator_old':
                    obj.visible = false
                    break;
                case 'creationtime_old':
                    obj.visible = false
                    break;
                case 'modifier_old':
                    obj.visible = false
                    break;
                case 'modifiedtime_old':
                    obj.visible = false
                    break;
                default:break;
            }
        })
        meta2.items.map(obj => {
            switch (obj.attrcode) {
                case 'creator':
                    obj.visible = false
                    break;
                case 'creationtime':
                    obj.visible = false
                    break;
                case 'modifier':
                    obj.visible = false
                    break;
                case 'modifiedtime':
                    obj.visible = false
                    break;
                default:break;
            }
        })
    }
    // 下一步方法
    nextHandle (selectData) {
        let props = this.props
        let {form, config} = props
        pk_psnjobs = selectData.map(function (item) {
            return item.data.values.pk_psnjob.value
        })
        let paramObj = {
            pageCode: config.pagecode,
            appCode: config.appcode,
            areaCode: 'dataBase,dataBefore,dataAfter',
            pk_psnjobs: pk_psnjobs
        }
        ajax({
            url: '/nccloud/hrcm/common/DataInitAction.do', // editColumn
            data: paramObj,
            success: (result) => {
                if (result.success) {
                    let data = result.data
                    let extendParam = data.extendParam
                    let rows = data.resultData.dataBase_add.rows
                    let rollBackFlag = data.resultData.rollBackFlag
                    let template = {
                        dataAfter_add: data.template.dataAfter_add,
                        dataBase_add: data.template.dataBase_add,
                        dataBefore_add: data.template.dataBefore_add,
                        formrelation: data.template.formrelation
                    }
                    props.meta.addMeta(template);
                    // this.setDataBeforeFormKey(props)
                    let values = rows[0].values
                    let contractnum = values.contractnum.value
                    // 获取可编辑的key
                    let items = props.meta.getMeta()['dataAfter_add'].items
                    let len = items.length 
                    let editColumn = []
                    for (let i=0;i < len; i++) {
                        if (items[i].visible === true && items[i].disabled === false) {
                            editColumn.push(items[i].attrcode)
                        }
                    }
                    this.setState({
                        formVisible: true,
                        editColumn,
                        contractnum,
                        rollBackFlag,
                        extendParam
                    }, function () {
                        form.setAllFormValue({'dataBase_add': {rows: rows}})
                        form.setFormItemsDisabled('dataBase_add', {
                            termmonth_old: true,
                            enddate_old: true,
                            ifprop_old: true, 
                            promonth_old: true, 
                            prop_unit_old: true, 
                            probegindate_old: true,
                            probenddate_old: true
                        })
                        form.setFormItemsRequired('dataBase_add', {
                            termmonth_old: false,
                            enddate_old: false,
                            promonth_old: false, 
                            prop_unit_old: false, 
                            probegindate_old: false,
                            probenddate_old: false
                        })
                        form.setFormStatus('dataBase_add', 'edit')
                        let attrMap = data.attrMap
                        let valueMap = data.valueMap
                        setFormAttrAndValue(attrMap, valueMap, props, 'dataBase_add', ['dataBase_add', 'dataAfter_add']) 
                    })
                }
            },
            error: (err) => {
                this.prevHandle()
                toast({
                    color: 'danger',
                    content: err.message
                })
                throw err
            }
        })
    }
    // 完成方法 调用新增保存接口
    doneHandle () {
        let props = this.props
        let state = this.state
        let {form, cardPagination, json, pageid, config} = props;
        if (!form.isCheckNow('dataBase_add')) {
            return false
        }
        saveValidate(props, 'dataBase_add', 'dataBase_add', ['dataBefore_add', 'dataAfter_add'] , 'extcard').then(() => {
            let formDataRows = form.getAllFormValue('dataBase_add').rows
            let formData = {
                model: {
                    rows: formDataRows
                }
            }
            let paramObj = {
                step: state.step,
                pk_org: props.pkOrg,
                modename: 'hi_psndoc_ctrt',
                formData: formData,
                appCode: config.appcode,
                editColumn: state.editColumn
            }
            if (parseInt(state.step) > 2) {
                paramObj = {
                    step: state.step,
                    pk_org: props.pkOrg,
                    appCode: config.appcode,
                    savedData: state.savedData
                }
            }
            ajax({
                url: `/nccloud/hrcm/make/${state.addSaveUrl}.do`,
                data: paramObj,
                success: (result) => {
                    if (result.success) {
                        this.setState({
                            step: result.data.step
                        }, function () {
                            if (result.data.step === '3') {
                                let savedData = result.data.savedData
                                this.setState({
                                    savedData: savedData,
                                    addSaveUrl: 'MakeAddSaveActionAfter'
                                }, function () {
                                    this.doneHandle()
                                    if (props.returnListOrCard && props.returnListOrCard() === 'cardList') {
                                        let pk_psndoc_sub = savedData[savedData.length - 1]
                                        props.initDataShow(pk_psndoc_sub)
                                        let allpks = cacheTools.get('allpks')
                                        allpks.push(pk_psndoc_sub)
                                        cardPagination.setCardPaginationId({id: pk_psndoc_sub, status: 1})
                                    }
                                })
                                return false
                            }
                            let title = json['cm6011-000126'] // 确定继续
                            if (result.data.step === '4') {
                                title = json['cm6011-000121'] // 确认生效
                            }
                            if (result.data.step !== '99') {
                                this.addSaveAfterTips(result.data.msg, title)
                            } else {
                                toast({
                                    color: 'success',
                                    content: json['cm6011-000122'] // 生效成功
                                })
                                this.setState({
                                    step: '0',
                                    addSaveUrl: 'MakeAddSaveAction'
                                })
                                this.props.setNewIncreasedDis(false)
                                if (this.props.refreshTableList) {
                                    this.props.refreshTableList()
                                }
                            }
                        })
                    }
                }
            })
        })
    }
    // 点击生效之后的提示
    addSaveAfterTips (message, title) {
        let json = this.props.json
        promptBox({
            color: 'warning',
            title: title, // 确认继续
            content: message,
            noFooter: false,
            noCancelBtn: false,
            beSureBtnName: json['cm6011-000057'], // 是
            cancelBtnName: json['cm6011-000058'], // 否
            beSureBtnClick: this.doneHandle.bind(this),
            hasCloseBtn:false,
            cancelBtnClick: this.cancelBtnClick.bind(this, title)
        })
    }
    cancelBtnClick (title) {
        let props = this.props
        let state = this.state
        let json = props.json
        this.setState({
            step: '0'
        })
        if (title === json['cm6011-000121']) {
            props.setNewIncreasedDis(false)
            if (props.refreshTableList) {
                props.refreshTableList()
            }
        }
        if (props.jumpToNode && title === json['cm6011-000121']) {
            props.jumpToNode(state.savedData, 'change')
        }
    }
    onClose () {
        this.setState({
            step: '0'
        })
        this.props.setNewIncreasedDis(false)
        if (this.state.rollBackFlag) {
            this.CodeRollBaceAction()
        }
    }
    // 上一步的回调
    prevHandle () {
        this.setState({
            step: '0'
        })
        if (this.state.rollBackFlag) {
            this.CodeRollBaceAction()
        }
    }
    // 调用合同编码回滚接口
    CodeRollBaceAction () {
        let props = this.props
        let state = this.state
        let contractnum = state.contractnum
        let codeList = []
        if (contractnum && contractnum.indexOf(',') !== -1) {
            codeList = contractnum.split(',')
        } else {
            codeList.push(contractnum) 
        }
        let paramObj = {
            pk_org: props.pkOrg,
            codeList: codeList
        }
        ajax({
            url: '/nccloud/hrcm/common/CodeRollBackAction.do',
            data: paramObj,
            success: (result) => {
                if (result.success) {
                    
                }
            }
        })
    }
    // 表单改变之后的触发函数
    onAfterEvent (props, moduleId, key, value, oldValue) {
        let { config } = this.state;
        chectFormAction(key, 'dataBase_add', props, ['dataBase_add', 'dataAfter_add'], config.appcode, this.state.extendParam)
    }
    //编辑FormCard前方法
    handleEditBefore(props, moduleId, key, value,data){
        if(key == 'pk_conttext'){
            let meta = this.props.meta.getMeta();
            let pk_org = this.props.pkOrg;
            meta['dataAfter_add'].items.find(item => item.attrcode === key).queryCondition = function () {
                return {
                    "pk_org": pk_org,
                    "GridRefActionExt": "nccloud.web.hrcm.make.sqlbuilder.ContModelGridSqlBuilder"
                }
            };
            this.props.meta.setMeta(meta);
        }
        return true;
    }
    render () {
        const {form} = this.props
        return (
            <div className="addFormCon">
                {
                    this.state.formVisible ? 
                    form.createForm('dataBase_add', {
                        expandArr: ['dataAfter_add'],
                        onAfterEvent: this.onAfterEvent.bind(this),
                        onBeforeEvent: this.handleEditBefore.bind(this)
                    }) : ''
                }
            </div>
        )
    }
}
export default AddForm